package articlevalidator

import (
	"errors"
	"fmt"
	"time"
	"yunj/app/enum/articleenum"
	"yunj/app/model"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
	"gorm.io/gorm"
)

type Article struct {
	validate.Validator
	Article     *model.Article
	ArticleAttr *model.ArticleAttr
}

func (v *Article) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "Add" || scene == "Edit" {
		err = v.handleArticleDatas(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Article) handleArticleDatas(datas map[string]interface{}) (err error) {
	currTime := time.Now().In(time.Local)
	var article model.Article
	var articleAttr model.ArticleAttr
	// id
	id := util.MapUint64Value(datas, "id")
	if id > 0 {
		dbErr := global.MySQL.Model(&model.Article{}).Where("id = ? and state <> ?", id, stateenum.DELETED).First(&article).Error
		if dbErr != nil {
			err = fmt.Errorf("文章数据异常！%v", dbErr)
			return
		}
		dbErr = global.MySQL.Model(&model.ArticleAttr{}).Where("article_id = ?", id).First(&articleAttr).Error
		if dbErr != nil && !errors.Is(dbErr, gorm.ErrRecordNotFound) {
			err = fmt.Errorf("文章属性数据异常！%v", dbErr)
			return
		}
	} else {
		article = model.Article{}
		articleAttr = model.ArticleAttr{}
	}
	// article
	article.Title = util.MapStrValue(datas, "title")
	article.CategoryId = util.MapUint64Value(datas, "category_id")
	article.Keywords = util.MapStrValue(datas, "keywords")
	article.Cover = util.MapStrValue(datas, "cover")
	article.Status = util.MapIntValue(datas, "status", articleenum.STATUS_PENDING)
	article.LastUpdateTime = currTime.Unix()
	if article.Id <= 0 {
		article.State = stateenum.NORMAL
		article.CreateTime = currTime.Unix()
	}
	v.Article = &article
	// article_attr
	articleAttr.Content = util.MapStrValue(datas, "content")
	if article.Id > 0 {
		articleAttr.ArticleId = article.Id
	}
	v.ArticleAttr = &articleAttr
	return
}
